package com.tianruan.psychological.common.utils;

import java.io.Serializable;
import java.util.regex.Pattern;

/**
 * @Author: Dong
 * @Email: dong980514280@gmail.com
 * @Create: 2019-11-19 10:34
 * @PS
 */
public class RegexUtils implements Serializable {

    /**
     * 手机正则表达式
     */
    private static final String PHONE_REGEX = "^((13[0-9])|(14[579])|(15([0-3,5-9]))|(16[6])|(17[0-3,5-8])|(18[0-9]|19[89]))\\d{8}$";

    /**
     * 邮箱正则表达式
     */
    private static final String EMAIL_REGEX = "^[a-zA-Z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$";

    /**
     * 域名正则表达式
     */
    private static final String DOMAIN_REGEX
            = "^https{0,1}://[a-zA-Z0-9\u4e00-\u9fa5]+(.[a-zA-Z0-9_-]+)+$";

    private static final String DOMAIN_SUFFIX = "abogado|abudhabi|ac|academy|accountant|ad|adult|ae|aero|af|africa|ag|ai|airforce|al|alsace|am|amsterdam|an|analytics|anquan|antivirus|ao|app|aq|aquitaine|ar|arab|archi|architect|army|art|as|asia|at|attorney|au|auction|audible|auto|autoinsurance|autos|aw|az" +
            "|ba|baby|band|banque|bar|barcelona|bargains|baseball|bayern|bb|bcn|bd|be|beats|beauty|beer|beknown|berlin|best|bet|bf|bg|bh|bible|bid|bike|bingo|bio|biz|bj|black|blackfriday|blog|blue|bm|bn|bo|boats|bom|boo|book|booking|boston|bot|boutique|boutique|box|br|broadway|broker|brussels|bs|bt|budapest|builders|business|buzz|bv|bw|by|bz|bzh" +
            "|ca|cab|cafe|cal|call|cam|camera|camp|cancerresearch|capetown|car|caravan|care|carinsurance|cars|casa|casa|casa|casino|cat|catalonia|catering|catholic|cc|cc|cd|center|ceo|cf|cfp|cg|ch|channel|charity|chat|cheap|christmas|church|ci|circle|city|ck|cl|claims|cleaning|click|clothing|cloud|club|club|club|cm|cn|co|coach|coach|codes|coffee|college|college|cologne|com|com.cn|community|company|compare|computer|condos|connectors|construction|consulting|contact|contact|contact|contractors|contruction|cooking|cooking|cool|cool|coop|corp|corsica|country|coupon|coupons|courses|cpa|cr|credit|creditcard|cricket|cruise|cruises|cu|cv|cx|cy|cymru|cz" +
            "|dad|dance|dance|data|date|dating|day|dds|de|deal|deal|dealer|deals|deals|degree|delivery|democrat|dental|dentist|desi|design|design|dev|diamonds|diamonds|diet|digital|direct|direct|directory|discount|discover|diy|dj|dk|dm|do|docs|doctor|dog|doha|domains|donuts|dot|download|drive|dubai|durban|dvr|dz" +
            "|earth|eat|ec|eco|ecom|edu|education|education|ee|eg|eh|email|energy|engineer|engineering|enterprises|equipment|er|es|esq|estate|et|eu|eus|events|events|exchange|expert|exposed|express" +
            "|fail|faith|faith|family|fan|fans|farm|farmers|fashion|fashion|fashion|fast|feedback|fi|film|final|finance|financial|financialaid|finish|fire|fish|fishing|fit|fitness|fj|fk|flights|flights|florist|flowers|fly|fm|fo|foo|food|food|football|football|forsale|forsale|forum|foundation|fr|free|frontdoor|fun|fun|fund|furniture|furniture|futbol|fyi" +
            "|ga|gal|gallery|game|game|games|games|garden|garden|gay|gay|gd|ge|ge|gent|gf|gg|gh|gi|gift|gifts|gives|giving|gl|glass|global|gmbh|gn|gold|golf|golf|gop|got|gov|gov.cn|gp|gq|graphics|gratis|green|gripe|grocery|group|gs|gt|gt|gu|guide|guide|guitars|guru|gw|gy" +
            "|hair|halal|hamburg|hangout|haus|health|healthcare|help|help|helsinki|here|hiphop|hiv|hk|hm|hn|hockey|hockey|holdings|holiday|holiday|home|home|home|homegoods|homes|homesense|horse|hospital|host|hosting|hot|hotel|hotel|hoteles|hotels|hotels|hotels|house|house|how|hr|ht|hu" +
            "|icu|id|idn|idv|ie|il|im|immo|immobilien|in|inc|indiands|industries|info|ing|ink|ink|institute|insurance|insure|int|international|investments|io|iq|ir|ira|irish|is|islam|islam|ist|istanbul|it" +
            "|je|jetzt|jewelry|jewelry|jm|jo|jobs|joburg|jot|joy|jp|juegos|justforu" +
            "|kaufen|ke|kg|kh|ki|kid|kid|kids|kids|kim|kinder|kitchen|kiwi|km|kn|koeln|kosher|kp|kr|kw|ky|kyoto|kz" +
            "|la|land|lat|latino|law|lawyer|lb|lc|lease|legal|lgbt|li|liason|life|lifestyle|lighting|lighting|like|like|limited|link|live|live|living|lk|llc|llp|loan|loans|locker|loft|loft|lol|lol|london|lotto|love|lr|ls|ltd|ltda|luxe|luxury" +
            "|ma|madrid|mail|maison|makeup|managment|map|market|marketing|markets|matrix|mba|mc|md|me|media|medical|meet|meet|melbourne|meme|memorial|men|men|menu|mg|mh|miami|mil|mk|ml|mls|mm|mn|mo|mobi|mobile|moda|moda|moi|mom|money|mortgage|moscow|moto|motorcycles|mov|movie|movistar|mp|mr|ms|mt|mu|museum|music|music|mutualfunds|mv|mw|mx|my|mz" +
            "|na|nagoya|name|navy|nc|ne|net|net.cn|network|new|news|next|nf|ng|ngo|ngo|ni|ninja|nl|no|now|np|nr|nrw|nu|nyc|nz" +
            "|okinawa|om|one|ong|onl|online|ooo|open|org|org.cn|organic|origins|osaka" +
            "|pa|page|paris|partners|parts|party|party|party|patch|pay|pe|persiangulf|pet|pets|pf|pg|ph|pharmacy|phd|phone|photo|photo|photography|photography|photos|photos|physio|pics|pictures|pid|pin|ping|pink|pizza|pizza|pk|pl|place|play|plumbing|plus|pm|pn|poker|porn|post|pr|press|pro|prod|productions|prof|progressive|prom|properties|property|protection|ps|pt|pub|pw|py" +
            "|qa|qpon|quebec" +
            "|racing|radio|re|read|realestate|realtor|realty|recipes|red|red|rehab|reise|reisen|rent|rentals|repair|report|republican|rest|restaurant|restaurant|review|reviews|rio|ro|rocks|rodeo|roma|room|room|ru|rugby|rugby|ruhr|run|rw" +
            "|sa|saarland|safe|sale|sale|salon|sarl|save|sb|sc|school|school|schule|science|sd|se|search|secure|security|services|sex|sexy|sg|sh|shoes|shoes|shop|shopping|shopyourway|shouji|show|si|silk|singles|singles|site|sk|ski|skin|sm|smile|sn|so|soccer|soccer|social|social|software|solar|solutions|song|soy|spa|sport|sport|sports|sports|spot|sr|srl|st|star|stockholm|storage|store|stroke|studio|study|style|sucks|supplies|supply|surf|sv|swiss|swiss|sy|sydney|sz" +
            "|taipei|tatoo|tattoo|tax|taxi|tc|td|team|tech|technology|tel|tennis|tf|tg|th|thai|thai|theater|theatre|tickets|tienda|tips|tips|tires|tirol|tj|tk|tl|tm|tn|to|today|tokyo|top|total|tour|tour|tours|tours|town|toys|toys|tp|tr|trade|trading|training|translations|travel|travelers|travelers|travelersinsurcance|trust|tt|tunes|tv|tv|tw|tz" +
            "|ua|ug|uk|um|university|university|uno|us|uy|uz" +
            "|va|vacations|vacations|vc|ve|vegas|ventures|ventures|versicherung|versicherung|vet|vg|vi|viajes|villas|vin|vip|vivo|vn|vodka|voyage|vu|vuelos" +
            "|wales|wang|watch|watches|weather|webcam|wed|wedding|wedding|wf|wien|wine|wine|winners|winwinners|work|works|world|wow|ws|wtf" +
            "|xxx|xyz|xyz" +
            "|yachts|ye|yoga|yokohama|you|yr|yt|yu" +
            "|za|zero|zm|zone|zuerich|zw" +
            "|δοκιμή|дети|испытание|мкд|мон|москва|онлайн|орг|рф|сайт|срб|укр|қаз|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عمان|فلسطين|قطر|مصر|مليسيا|موقع|پاکستان|परीक्षा|भारत|संगठन|বাংলা|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|გე|みんな|テスト" +
            "|世界|中信|中国|中国|中國|中文网|公司|公司|公益|台湾|台灣|商城|商标|在线|我爱你|政务|新加坡|机构|测试|測試|游戏|移动|组织机构|网址|网络|网络|集团|香港|삼성|테스트|한국";

    /**
     * 是否是手机
     * @param phoneNum 手机号
     * @return
     */
    public static boolean isMobile(String phoneNum) {
        if (phoneNum == null) {
            return false;
        }
        boolean isPhoneNumber = Pattern.matches(PHONE_REGEX, phoneNum);
        return isPhoneNumber;
    }

    /**
     * 判断是否是电子邮箱
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null) {
            return false;
        }
        boolean isEmail = Pattern.matches(EMAIL_REGEX, email);
        return isEmail;
    }

    /**
     * 是否是域名（只是判断域名）
     * @param domain
     * @return
     */
    public static boolean isDomain(String domain) {
        if (domain == null) {
            return false;
        }
        domain = domain.toLowerCase();
        // 最后一个句号位置
        int lastP = domain.lastIndexOf('.');
        if (lastP != -1) {
            // 判断是否是域名后缀
            if (!StringUtils.inString(domain.substring(lastP + 1), DOMAIN_SUFFIX.split("\\|"))) {
                return false;
            }
        } else {
            return false;
        }
        boolean isDomain = Pattern.matches(DOMAIN_REGEX, domain.substring(0, lastP));
        return isDomain;
    }

    /**
     * 是否是url
     * @param url
     * @return
     */
    public static boolean isUrl(String url) {
        if (url == null) {
            return false;
        }

        // 最后一个句号位置
        int lastP = url.indexOf('/', 8);
        if (lastP == -1) {
            return isDomain(url);
        } else {

        }
        return true;
    }

}
